<script setup>
import {Notification} from "@arco-design/web-vue";
import { ref} from 'vue'
import {xml} from "@codemirror/lang-xml";
import {Codemirror} from "vue-codemirror";
import apiAll from "@/api/apiAll.js";
import submitUpdate from './submitUpdate.vue'
import routerList from './routerList.vue'
import xmlFormat from 'xml-formatter';

const extensions = [xml()];
const code = ref('')
const submitUpdateRef = ref()
const routerListRef = ref()
const loading = ref(true)
const xmlRef = ref()
const isUpdate = ref(false)
const needFormatter = ref(false)

const loadData = () => {
  loading.value = true
  apiAll.configApi.get().then(res => {
    code.value = res.data
  }).finally(() => {
    loading.value = false
  }, 500)
}
const submit = () => {
  if (!isUpdate.value) {
    Notification.info('配置未改动')
    return
  }
  if (needFormatter.value) {
    Notification.info('存在更新，请先格式化配置')
    return;
  }
  submitUpdateRef.value.show(xmlRef.value.modelValue)
}
const xmlformatter = () => {
  loading.value = true
  const xml = xmlRef.value.modelValue
  try {
    code.value = xmlFormat(xml)
  } catch (e) {
    Notification.error('格式化失败，请检查配置')
    return
  } finally {
    setTimeout(() => {
      loading.value = false
    }, 500)
  }
  Notification.success('格式化成功')
  setTimeout(() => {
    needFormatter.value = false
  }, 500)
}
const sample = () => {
  window.open('/api/config/sample')
}
const seeRouterList = () => {
  routerListRef.value.show()
}

const handleReady = () => {
  loadData()
}
const handlerChange = (v) => {
  if (loading.value === false) {
    isUpdate.value = true
    needFormatter.value = true
  }
}
</script>

<template>
  <div class="flex-column" style="width: 100%">
    <a-space>
      <a-button @click="submit" type="primary">保存修改配置</a-button>
      <a-button @click="xmlformatter" type="primary">格式化配置</a-button>
      <a-button @click="seeRouterList" type="outline">路由转发列表</a-button>
      <a-button @click="sample" type="outline">查看列表样例</a-button>
    </a-space>
    <a-divider/>
    <a-spin :loading="loading" tip="加载中...">
      <Codemirror
          ref="xmlRef"
          v-model="code"
          placeholder="Code goes here..."
          :style="{ height: '74vh' }"
          :autofocus="true"
          :indent-with-tab="true"
          :tab-size="2"
          :extensions="extensions"
          @ready="handleReady"
          @change="handlerChange"
      />
    </a-spin>

    <submitUpdate ref="submitUpdateRef"/>
    <routerList ref="routerListRef"/>
  </div>
</template>

<style scoped>

</style>